package com.chen.demo.javase.juc;

import java.util.Queue;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

/**
 * 自定义不可重入锁
 * <p>
 * state状态值：
 * 1: 表示已持有该锁
 *
 * @author chenhongwei
 * @date 2019/9/14 17:05
 **/
public class CustomerNonReentrantLock implements Lock {
    /**
     * 创建sync来做具体工作
     */
    private final Sync sync = new Sync();

    @Override
    public void lock() {
        sync.acquire(1);
    }

    @Override
    public void lockInterruptibly() throws InterruptedException {
        sync.acquireInterruptibly(1);
    }

    @Override
    public boolean tryLock() {
        return sync.tryAcquire(1);
    }

    @Override
    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        return sync.tryAcquireNanos(1, unit.toNanos(time));
    }

    @Override
    public void unlock() {
        sync.release(1);
    }

    @Override
    public Condition newCondition() {
        return sync.newCondition();
    }

    /**
     * 内部帮助类
     */
    private static class Sync extends AbstractQueuedSynchronizer {
        /**
         * 锁是否被持有
         *
         * @return true:
         */
        @Override
        protected boolean isHeldExclusively() {
            return getState() == 1;
        }

        @Override
        protected boolean tryAcquire(int arg) {
            assert arg == 1;
            if (compareAndSetState(0, 1)) {
                setExclusiveOwnerThread(Thread.currentThread());
                setState(1);
                return true;
            }
            return false;
        }

        /**
         * 释放锁
         *
         * @param arg 状态值
         * @return true:成功
         */
        @Override
        protected boolean tryRelease(int arg) {
            assert arg == 1;
            if (getState() == 0) {
                throw new IllegalMonitorStateException();
            }
            setExclusiveOwnerThread(null);
            setState(0);
            return true;
        }

        Condition newCondition() {
            return new ConditionObject();
        }

    }


    final static CustomerNonReentrantLock lock = new CustomerNonReentrantLock();
    final static Condition notFull = lock.newCondition();
    final static Condition notEmpty = lock.newCondition();
    final static Queue<String> queue = new LinkedBlockingQueue<String>();
    final static int queueSize = 10;

    /**
     * 观察者消费者模式测试
     *
     * @param args args
     */
    public static void main(String[] args) throws InterruptedException {
        Thread produce = new Thread(new Runnable() {
            @Override
            public void run() {
                lock.lock();
                try {
                    //队列满，等待
                    while (queue.size() == queueSize) {
                        notEmpty.await();
                    }
                    //添加队列元素
                    queue.add("ele");
                    System.out.println("生产者生产完成.");
                    //唤醒消费线程
                    notFull.signalAll();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }

            }
        });

        Thread consumer = new Thread(new Runnable() {
            @Override
            public void run() {
                lock.lock();
                System.out.println("消费者获取锁");
                try {
                    //队列为空，停止消费
                    while (queue.size() == 0) {
                        System.out.println("队列为空");
                        notFull.await();
                    }
                    //
                    String ele = queue.poll();
                    System.out.println("消费者消费完成.");
                    //唤醒生产线程
                    notEmpty.signalAll();

                } catch (Exception e) {
                    e.printStackTrace();
                    ;
                } finally {
                    lock.unlock();
                }
            }
        });

        produce.start();
        Thread.sleep(20);
        consumer.start();
    }
}
